package com.pk.springbootsy1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pk.springbootsy1.dto.TUserDto;
import com.pk.springbootsy1.entity.TUser;
import com.pk.springbootsy1.enums.RoleEnum;
import com.pk.springbootsy1.mapper.TUserMapper;
import com.pk.springbootsy1.service.TUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper,TUser> implements TUserService {
    @Autowired
    private TUserMapper tUserMapper;

    @Override
    public boolean login(String username, String password) {
        LambdaQueryWrapper<TUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TUser::getLoginName, username);
        TUser loginUser = tUserMapper.selectOne(lambdaQueryWrapper);
        if (loginUser == null) {
            return false;
        } else if (!loginUser.getPassword().equals(DigestUtils.md5Hex(password))) {
            return false;
        }else {
            loginUser.setLastLoginTime(new Date());
            return tUserMapper.updateById(loginUser) > 0;
        }

    }


    @Override
    public boolean register(TUser tUser) {
        tUser.setType(RoleEnum.USER.getCode());
        tUser.setPassword(DigestUtils.md5Hex(tUser.getPassword()));
        LambdaQueryWrapper<TUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TUser::getLoginName, tUser.getLoginName());
        TUser register = tUserMapper.selectOne(lambdaQueryWrapper);
        if (register != null) {
            return false;
        }
        return tUserMapper.insert(tUser) > 0;
    }

    @Override
    public TUser selectByUsername(String username) {
        LambdaQueryWrapper<TUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TUser::getLoginName, username);
        return tUserMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public List<TUserDto> listTUserDto() {
        return TUserDto.convert(tUserMapper.selectList(null));
    }

    @Override
    public boolean reset(TUser tUser) {
        //将密码重置为123456
        String password = "123456";
        if (selectByUsername(tUser.getLoginName()) == null){
            return false;
        }else {
            tUser.setPassword(DigestUtils.md5Hex(password));
            return tUserMapper.updateById(tUser) > 0;
        }

    }
}
